<template>
    <div class="setting-container wrapper"  @click="levelShowTree = false;appShowTree = false;modelShowTree = false">
        <div class="setting-box">
            <!--右侧详情-->
            <div class="setting-detail">
                <el-form label-position="top" :inline="true" v-model="filter" >
                    <el-row>

                    <el-col :span="4">
                        <el-form-item label="权限名称：">
                             <el-input v-model="filter.name" size="small" placeholder="权限名称">
                              </el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="4" >
                        <el-form-item label="所属模块：">
                            <el-input v-model="filter.modelName" icon="caret-bottom" placeholder="所属模块"  size="small"></el-input>
                            <div @click.stop="modelShowTree=!modelShowTree"
                                 style="position: absolute;top:3px;left:0;z-index: 10;width: 100%;height: 30px;">
                                <div v-show="modelShowTree" class="tree-select inline-tree" >
                                    <el-tree :data="modelData"
                                             show-checkbox
                                             default-expand-all
                                             node-key="id"
                                             ref="searchModelTree"
                                             @check-change="modelCheckChange"
                                             :props="levelTreeProps">
                                    </el-tree>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4" >
                        <el-form-item label="权限等级：">
                            <el-input v-model="filter.powerLevel" icon="caret-bottom" placeholder="权限等级"  size="small"></el-input>
                            <div @click.stop="levelShowTree=!levelShowTree"
                                 style="position: absolute;top:3px;left:0;z-index: 10;width: 100%;height: 30px;">
                                <div v-show="levelShowTree" class="tree-select inline-tree" >
                                    <el-tree :data="levelData"
                                             show-checkbox
                                             default-expand-all
                                             node-key="id"
                                             ref="searchPowerTree"
                                             @check-change="handleCheckChange"
                                             :props="levelTreeProps">
                                    </el-tree>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>

                    <el-col :span="4" >
                        <el-form-item label="审批等级：">
                            <el-input v-model="filter.approvalLevel" icon="caret-bottom" placeholder="审批等级"  size="small"></el-input>
                            <div @click.stop="appShowTree=!appShowTree"
                                 style="position: absolute;top:3px;left:0;z-index: 10;width: 100%;height: 30px;">
                                <div v-show="appShowTree" class="tree-select inline-tree" >
                                    <el-tree :data="levelData"
                                             show-checkbox
                                             default-expand-all
                                             node-key="id"
                                             ref="searchApprovalTree"
                                             @check-change="approvalCheckChange"
                                             :props="levelTreeProps">
                                    </el-tree>
                                </div>
                            </div>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :span="4">
                    <div class="search-bottom-btn">
                        <el-button size="small" type="primary" icon="el-icon-delete" @click="clearData">清空筛选条件</el-button>
                        <el-button size="small" type="primary" icon="el-icon-search" @click="filterData">查询</el-button>
                    </div>
                </el-row>
                </el-form>

                <!--操作列表-->
                <div class="edit-list">
                    <el-table @selection-change="handleSelectionChange" :data="powerSettingList" style="width: 100%" stripe>
                        <el-table-column type="index" width="80" ></el-table-column>
                        <!-- <el-table-column type="selection" width="50"></el-table-column> -->
                        <el-table-column label="权限名称" min-width="160"  className="asdt">
                            <template scope="scope"><div>{{scope.row.name}}</div></template>
                            <!-- <template scope="scope"><div class='name-btn' @click="powerShow(scope.row)">{{scope.row.name}}</div></template> -->
                        </el-table-column>
                        
                        <el-table-column label="所属模块"  min-width="180" prop="appModuleName"  className="asds"></el-table-column>
                        <el-table-column label="权限URL" width="260" prop="url"  className="asdt"></el-table-column>
                        <el-table-column label="权限等级" min-width="100" prop="minUseLevel"  className="asdt"></el-table-column>
                        <el-table-column label="审批等级" min-width="100" prop="maxApproveLevel"  className="asds"></el-table-column>
                        
                        <el-table-column label="备注" width="200" prop="description"  className="asdt"></el-table-column>
                        <el-table-column fixed="right" label="操作" width="120" align="center"  className="asdt">
                            <template scope="scope">
                                <el-button @click="powerShow(scope.row,'sigle')" size="mini" type="primary" icon="share">分配权限</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </div>

                <!--分页-->
                <div class="pagination">
                    <el-pagination
                            @size-change="handleSizeChange"
                            @current-change="handleCurrentChange"
                            :current-page="currentSettingPage"
                            :page-sizes="pageSizes"
                            :page-size="50"
                            layout="total, sizes,prev, pager, next, jumper"
                            :total="totalSettingCount">
                    </el-pagination>
                </div>
            </div>
        </div>

        <!--摸态框-->
        <el-dialog @close="handleDialogClose" :visible.sync="importVisible" class="import-dialog" >
            <span slot="title">{{powerTitle}}</span>
            <div class="import-opera">
                <!--左侧树-->
                <div class="setting-leftnav">
                    <div class="top-panel"><i class='el-icon-menu'></i>&nbsp;部门</div>
                    <el-tree
                            :data="regions"
                            :props="props"
                            :load="loadNode"
                            check-strictly
                            highlight-current
                            lazy
                            accordion
                            @node-click = "handleNodeClick">
                    </el-tree>
                </div>
                <el-button @click="pushList" class="add-btn" type="primary" icon="el-icon-d-arrow-right"></el-button>
                <!--右侧列表-->
                <div class="setting-rightbox">
                    <div class="import-list">
                        <el-tag v-for='(item,i) in ListDetail' :key="item.id" @close='closeTag(item,i)' :closable="true" type="primary">{{item.name}}</el-tag>
                    </div>
                    <el-form>
                        <el-form-item>
                            <el-button @click="Submit" type="primary" icon="el-icon-upload2" size="small">保存</el-button>
                            <el-button @click="importVisible = false" type="warning" icon="el-icon-close"  size="small">取消</el-button>
                        </el-form-item>
                    </el-form>
                </div>
            </div>
        </el-dialog>
    </div>
</template>
<style>
</style>
<script>
    import Vue from 'vue'
    import axios from '~/plugins/axios'
    import * as types from '../../../store/mutation-types/power-setting/index';
    import { mapGetters, mapActions, mapMutations} from 'vuex';
    import { Row,Col,Icon,Menu,Submenu,MenuItemGroup,MenuItem,Button,Checkbox,Table,TableColumn,Tooltip,Dialog,Input,Form,FormItem,Tag,Tree,Select,Option,Message,MessageBox,Pagination,Card } from 'element-ui'
    import { ACTIVEINDEX } from '../../../store/mutation-types/left-menu/index';

    Vue.use(Row);
    Vue.use(Col);
    Vue.use(Menu);
    Vue.use(Submenu);
    Vue.use(MenuItemGroup);
    Vue.use(MenuItem);
    Vue.use(Button);
    Vue.use(Checkbox);
    Vue.use(Table);
    Vue.use(TableColumn);
    Vue.use(Dialog);
    Vue.use(Input);
    Vue.use(Form);
    Vue.use(FormItem);
    Vue.use(Tag);
    Vue.use(Tree);
    Vue.use(Select);
    Vue.use(Option);
    Vue.use(Pagination);
    Vue.use(Icon);
    Vue.use(Card);
    Vue.use(Tooltip);

    Vue.prototype.$message = Message;
    Vue.prototype.$confirm = MessageBox.confirm;

    export default{
        head(){
            return {
                title: "部门权限分配"
            }
        },
        data () {
            return {
                tabName: '部门权限分配',
                powerTitle:'',
                filter:{
                    name:'',
                    modelName:'全部',
                    modelId:'',
                    powerLevel:'全部',
                    powerLevelId:'',
                    approvalLevel:'全部',
                    approvalLevelId:'',
                    pageSize:50,
                    pageNum:1
                },
                levelShowTree:false,
                appShowTree:false,
                modelShowTree:false,
                //modelData:[],
                levelData:[{
                    id: "11",
                    label: '全部',
                    children: [
                    {id: "0",label: '0级'},
                    {id: "1",label: '1级'},
                    {id: "2",label: '2级'},
                    {id: "3",label: '3级'},
                    {id: "4",label: '4级'},
                    {id: "5",label: '5级'},
                    {id: "6",label: '6级'},
                    {id: "7",label: '7级'},
                    {id: "8",label: '8级'},
                    {id: "9",label: '9级'},
                    {id: "10",label: '10级'}]
                }],
                levelTreeProps: {
                    label: 'label',
                    children: 'children'
                },
                multipleSelection:[],
                List:[],
                form:'',
                value:'',
                addValue:'',
                importVisible:false,
                subDisable:true,
                selectAll:false,
                ListTitle:'',
                ListTitleIn:'',
                ListDetail:[],
                deleteDepIds:[],
                insertDepIds:[],
                resourceId:null,
                nowData:null,
                defaultProps: {
                    children: 'children',
                    label: 'text'
                },
                team:[],//左侧树结构
                pageSizes: [10,30,50],
                addedList:[],
                regions: [],
                'check-strictly':true,
                'highlight-current':true,
                props: {
                    label: 'name',
                    children: 'zones'
                },
                count: 1
            }
        },
        watch: {
            levelShowTree(){
                if(this.levelShowTree == false)this.filter.powerLevel = this.filter.powerLevel || '全部';
            },
            appShowTree(){
                if(this.appShowTree == false)this.filter.approvalLevel = this.filter.approvalLevel || '全部'
            },
            modelShowTree(){
                if(this.modelShowTree == false)this.filter.modelName = this.filter.modelName || '全部'
            }
        },
        computed : {
            ...mapGetters({
                'powerSettingList' : 'getPowerSettingList',
                'totalSettingCount' : 'getPowerSettingTotalCount',
                'currentSettingPage' : 'getPowerSettingCurrentPage',
                'powerModuleList' : 'getPowerModuleList',
                'pageTabsList': 'getPageTabsList'
            }),
            modelData(){
                let list = [{
                    id:0,
                    label: '全部',
                    children: []
                }];
                for(let i = 0; i<this.powerModuleList.length; i++){
                    list[0].children.push({
                        id:this.powerModuleList[i].id,
                        label: this.powerModuleList[i].name
                    })
                }
                return list;
            }
        },
        created() {
            let filter = this.$store.getters.powerSettingFilter;
            if(filter){
                this.filter = filter;
            }
            let params = {
                page: this.filter.pageNum,
                size: this.filter.pageSize,
                appModuleId: this.filter.modelId,
                useLevel: this.filter.powerLevelId,
                approveLevel: this.filter.approvalLevelId,
                name: this.filter.name
            };

            this.getListData(params);
            //appId 应用系统id，crm默认为1
            this.getPowerModuleData({appId:1,page: 1 , size :0});
            //pageTab
            if(process.BROWSER_BUILD) {
                if(this.pageTabsList[this.pageTabsList.length-1].name == 'CRM') {
                    let arr = this.pageTabsList;
                    arr[arr.length-1].name = this.tabName;
                    this.$store.commit('PAGETABSLIST',{data:arr})
                }
            }
        },

        methods:{
            //搜索条件加入cookie
            setFilterCookie(){
                this.$store.commit('POWER_SETTING_FILTER',{data:this.filter});
            },
            handleChange(){},
            clearData(){
                this.$refs.searchPowerTree.setCheckedKeys([]);
                this.$refs.searchApprovalTree.setCheckedKeys([]);
                this.$refs.searchModelTree.setCheckedKeys([]);
                this.filter = {
                    name:'',
                    modelName:'全部',
                    modelId:'',
                    powerLevel:'全部',
                    powerLevelId:'',
                    approvalLevel:'全部',
                    approvalLevelId:'',
                    pageSize:50,
                    pageNum:1
                }
                //this.$refs.searchPowerTree.setCheckedKeys({id: "0",label: '0级'},true);
                //this.getListData({page: 1 , size :this.pageSize, appModuleId:''});
            },
            filterData(){
                let params = {
                    page: this.filter.pageNum,
                    size: this.filter.pageSize,
                    appModuleId: this.filter.modelId,
                    useLevel: this.filter.powerLevelId,
                    approveLevel: this.filter.approvalLevelId,
                    name: this.filter.name
                };
                this.getListData(params);
            },
            getLevelName(id){
                for(let i = 0; i<this.levelData[0].children.length; i++){
                    if(this.levelData[0].children[i].id == id){
                        return this.levelData[0].children[i].label;
                    }
                }
            },
            getModelName(id){
                for(let i = 0; i<this.modelData[0].children.length; i++){
                    if(this.modelData[0].children[i].id == id){
                        return this.modelData[0].children[i].label;
                    }
                }
            },
            //权限等级选中回调
            handleCheckChange(data,checked) {
                this.filter.powerLevel ='';
                let checkedId = this.$refs.searchPowerTree.getCheckedKeys(data,true);
                let checkedName = [];
                if(checkedId.length == this.levelData[0].children.length) {
                    this.filter.powerLevel = '全部'
                }else {
                    for(let i=0;i<checkedId.length;i++){
                        checkedName.push(this.getLevelName(checkedId[i]));
                    }
                    this.filter.powerLevel = checkedName.join(' / ');
                }
                this.filter.powerLevelId = checkedId.join(',');
                //this.filter.category = checkedName;
            },
            //审批等级选中回调
            approvalCheckChange(data,checked){
                this.filter.approvalLevel ='';
                let checkedId = this.$refs.searchApprovalTree.getCheckedKeys(data,true);
                let checkedName = [];
                if(checkedId.length == this.levelData[0].children.length) {
                    this.filter.approvalLevel = '全部'
                }else {
                    for(let i=0;i<checkedId.length;i++){
                        checkedName.push(this.getLevelName(checkedId[i]));
                    }
                    this.filter.approvalLevel = checkedName.join(' / ');
                }
                this.filter.approvalLevelId = checkedId.join(',');
                //this.filter.category = checkedName;
            },
            //模块选中回调
            modelCheckChange(data,checked){
                this.filter.modelName ='';
                let checkedId = this.$refs.searchModelTree.getCheckedKeys(data,true);
                let checkedName = [];
                if(checkedId.length == this.modelData[0].children.length) {
                    this.filter.modelName = '全部'
                }else {
                    for(let i=0;i<checkedId.length;i++){
                        checkedName.push(this.getModelName(checkedId[i]));
                    }
                    this.filter.modelName = checkedName.join(' / ');
                }
                this.filter.modelId = checkedId.join(',');
                //this.filter.category = checkedName;
            },

            handleSelectionChange(val) {
                this.multipleSelection = [];
                if(val.length){
                    for(let i = 0; i<val.length; i++){
                        this.multipleSelection.push(val[i].id)
                    }
                }else{
                    this.multipleSelection = [];
                }
              },
            handleNodeClick(data) {
                this.nowData = data
            },
            loadNode(node, resolve) {
                this.getJson(node.data.id||0).then((ret)=>{
                    if(ret.data.data){
                        return resolve(ret.data.data);
                    }
                    
                })
            },
            getJson(id){
                return axios.get(process.env.baseUrl+'/department/list', {params:{parentId:id
                }})
            },
            //刷新
            reFresh(){
                this.getListData({page: this.filter.pageNum , size :this.filter.pageSize, appModuleId:''});
            },

            //添加部门
            pushList(){
                let len = this.ListDetail?this.ListDetail.length:0;
                let n = 0;
                if(len && this.nowData){
                    for(let i = 0; i<len; i++){
                        if(this.ListDetail[i].id == this.nowData.id)n++;
                    }
                    if(n){
                        this.$message({ type: 'error', message: '部门已存在' });
                        return;
                    }
                }
                if(this.nowData){
                    this.ListDetail.push({'name':this.nowData.name,'id':this.nowData.id});
                    this.insertDepIds.push(this.nowData.id);
                }else{
                    this.$message({ type: 'warning', message: '请选择部门' });
                }
                
            },

            //获取权限详情--已关联部门列表
            powerShow(row,type){
                this.insertDepIds = [];
                this.deleteDepIds = [];
                //this.resourceId = [];
                // if(type == 'multiple'){//多选
                //     this.ListDetail = [];
                //     this.resourceId = this.multipleSelection;
                // }else{
                    this.powerTitle = "权限分配--"+row.name;
                    this.resourceId = row.id;
                    axios.get(process.env.baseUrl+'/appmoduleresource/query', {params:{id:row.id}})
                        .then((res)=>{
                        if(res.data.code == 0){
                            this.ListDetail = res.data.data.parmentList||[];
                        }
                    })
                // }
                // if(this.resourceId.length){
                     this.importVisible = true;
                // }else{
                //     this.$message({ type: 'error', message: '请先选择权限！'});
                // }
                
                
            },

            //获取权限列表
            getListData(params){
                this.setFilterCookie();
                this.$store.dispatch('powerSettingList',params);
            },
            //获取模块列表
            getPowerModuleData(option){
                this.$store.dispatch('powerModuleList',option);
            },

            //分页
            handleSizeChange(index){
              this.filter.pageSize = index;
              let params = {
                page: this.filter.pageNum,
                size: this.filter.pageSize,
                appModuleId: this.filter.modelId,
                useLevel: this.filter.powerLevelId,
                approveLevel: this.filter.approvalLevelId,
                name: this.filter.name
              };
              this.getListData(params);
            },

            handleCurrentChange(index){
                this.filter.pageNum = index;
                let params = {
                    page: this.filter.pageNum,
                    size: this.filter.pageSize,
                    appModuleId: this.filter.modelId,
                    useLevel: this.filter.powerLevelId,
                    approveLevel: this.filter.approvalLevelId,
                    name: this.filter.name
                  };
                this.getListData(params);
            },

            //保存
            Submit(){
                let params = {
                    resourceId:this.resourceId,
                    deleteDepIds:this.deleteDepIds,
                    insertDepIds:this.insertDepIds
                }
                axios.post(process.env.baseUrl+'/appmoduleresource/allocating', params)
                    .then((res)=>{
                    if(res.data.code ==0){
                        this.$message({ type: 'success', message: '修改成功！' });
                        this.ListDetail = [];
                        this.importVisible = false;
                    }else{
                        this.$message({ type: 'error', message: res.data.message.slice(0,30) });
                    }
                })

            },

            //删除操作项
            closeTag(item,i){
                //this.$confirm('确定要删除'+item.name+'的该权限吗?', '提示', {
                this.$confirm('该部门及其子部门将共同取消此权限，确认删除吗?', '提示', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning'
              }).then(() => {
                if(this.ListDetail[i].gmtCreate){
                    this.deleteDepIds.push(this.ListDetail[i].id)
                }
                this.ListDetail.splice(i,1);

              }).catch(() => {});
                
            },

            //关闭弹窗
            handleDialogClose(){
                this.ListTitle = '';
                this.ListTitleIn = '';
                this.ListDetail = [];
                this.importVisible = false;
            }
        }
    }
</script>

<style lang="scss">
.el-table .asdt>.cell{
            padding: 0px;
        }

.tree-select {
    position: absolute;
    left: 0;
    top: 100%;
    z-index: 1;
    width: 100%;
    margin-top: 5px;
    box-shadow: 0 2px 4px rgba(0,0,0,.12), 0 0 6px rgba(0,0,0,.04);
    height: 300px;
    overflow: auto;
}

.search-bottom-btn{
	/*margin-top: 30px;*/
    margin-bottom: 20px;
   /* padding-left: 15px;*/
    min-width: 200px;
}
.setting-container{
    .el-tree{
        min-height: 370px;
    }
    .el-card{
        min-height: 480px;
        box-shadow:none;
        border-radius:0;
    }
    .el-tree--highlight-current .el-tree-node.is-current>.el-tree-node__content{
        background: #20a0ff;
        color: #fff;
    }
    }
    .el-table__empty-block{

    }
    .name-btn{
      //cursor: pointer;
      color: #4db3ff;
    }
    .name-btn:hover{
      //font-weight:800;
    }
    .setting-title{
        margin: 20px 0;
    }
    .setting-box{
        margin: 0 auto;
        padding-right: 10px;
        position: relative;
    .pagination {
        margin-top: 10px;
    }
    }
    .setting-leftnav{
        width: 30%;
        min-height: 400px;
        text-align: left;
        float:left;
        background: #E4E8F1;
        margin-bottom:50px;
    }
    .import-opera:after{
        content:".";
        display:block;
        height:0;
        clear:both;
        visibility:hidden;
    }
    .top-panel{
        height: 48px;
        line-height: 48px;
        padding-left: 20px;
        font-weight: bold;
        border-top:1px solid #DFE6EC;
        border-bottom:1px solid #DFE6EC;
    }
    .setting-detail{
        min-height: 530px;
    }
    .top-edit{
        padding: 10px 10px;
        text-align: left;
        border:1px solid #DFE6EC;
    }
    .top-edit button{
        margin:0 10px;
    }
    .top-title{
        text-align: left;
    }
    .top-title span{
        display: inline-block;
        width: 280px;
        height: 30px;
        line-height: 30px;
        padding: 0 25px;
    }
    .top-title .left-title{
        border-right: 1px solid #DFE6EC;
    }
    .edit-list{
        width:100%;
    .el-tree{
        padding-left:0;
    }
    }
    .import-dialog{
    .add-btn{
        float: left;
        margin-top: 200px;
        margin-left: 5px;
    }
    .el-dialog--small{
        min-width: 770px;
        width: 40%;
    }
    .el-dialog__header{
        margin-bottom: 20px;
        text-align: left;
    }
    .el-dialog--small .el-dialog__body{
        padding: 5px;
        text-align: center;
    }
    .import-tips{
        font-size: 16px;
    }
    .el-tag{
        margin-left:3px;
    }
    .inner-input input{
        width: 156px;
    }
    .setting-rightbox{
        float:right;
        width: 63%;
        min-width: 430px;
    }
    .import-list{
        min-height: 350px;
        border:1px solid #DFE6EC;
        border-radius:5px;
        padding: 30px 30px;
        margin: 0 10px 10px 0;
    }
    .dialog-footer{
        text-align: center;
    }
    }

</style>